import format from "./helper/format.js"
import isUploadFile from "./helper/isUploadFile.js"

/**
 * 参数配置参考：
 *   > axios          https://www.npmjs.com/package/axios#request-config
 *   > uniapp request https://uniapp.dcloud.io/api/request/request
 *   > uniapp upload  https://uniapp.dcloud.io/api/request/network-file
 * @param {object} config
 */
function uniappAdapter(config = {}) {
  return new Promise(function dispatchUniApp(resolve, reject) {
    const uniConfig = format(config, resolve, reject)
    // Handle cancellation
    let requestTask = null
    if (config.cancelToken) {
      config.cancelToken.promise.then(function onCanceled(cancel) {
        if (!requestTask) { return }
        requestTask.abort()
        reject(cancel)
        requestTask = null
      })
    }
    // Send the request
    if (isUploadFile(config)) {
      requestTask = uni.uploadFile(uniConfig)
    } else {
      requestTask = uni.request(uniConfig)
    }
  })
}

export default uniappAdapter
